package com.ruoyi.customer.service.impl;

import java.util.*;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.PrimaryKeyIdUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.customer.api.domain.CustomerManagement;
import com.ruoyi.customer.domain.CustomerDeviceBindVO;
import com.ruoyi.customer.service.ICustomerManagementService;
import com.ruoyi.device.domain.Device;
import com.ruoyi.device.enums.OwnershipEnum;
import com.ruoyi.device.mapper.DeviceMapper;
import com.ruoyi.device.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.customer.mapper.CustomerDeviceBindMapper;
import com.ruoyi.customer.domain.CustomerDeviceBind;
import com.ruoyi.customer.service.ICustomerDeviceBindService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户设备绑定Service业务层处理
 * 
 * @author luogongquan
 * @date 2024-09-09
 */
@Service
public class CustomerDeviceBindServiceImpl implements ICustomerDeviceBindService 
{
    @Autowired
    private CustomerDeviceBindMapper customerDeviceBindMapper;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private ICustomerManagementService customerManagementService;
    /**
     * 查询用户设备绑定
     * 
     * @param id 用户设备绑定主键
     * @return 用户设备绑定
     */
    @Override
    public CustomerDeviceBind selectCustomerDeviceBindById(Long id)
    {
        return customerDeviceBindMapper.selectCustomerDeviceBindById(id);
    }

    /**
     * 查询用户设备绑定列表
     * 
     * @param customerDeviceBind 用户设备绑定
     * @return 用户设备绑定
     */
    @Override
    public List<CustomerDeviceBind> selectCustomerDeviceBindList(CustomerDeviceBind customerDeviceBind)
    {
        return customerDeviceBindMapper.selectCustomerDeviceBindList(customerDeviceBind);
    }

    /**
     * 新增用户设备绑定
     * 
     * @param customerDeviceBind 用户设备绑定
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertCustomerDeviceBind(CustomerDeviceBind customerDeviceBind)
    {
        List<Long> deviceIds = customerDeviceBind.getDeviceIds();
        if(deviceIds.isEmpty()){
            throw new ServiceException("绑定设备不能为空");
        }
        List<String> deviceTypes = customerDeviceBind.getDeviceTypes();
        Date nowDate = DateUtils.getNowDate();
        List<CustomerDeviceBind> insertList = new ArrayList<>(deviceIds.size());
        for (int i = 0; i < deviceIds.size(); i++) {
            CustomerDeviceBind bind = new CustomerDeviceBind();
            bind.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
            bind.setBindTime(nowDate);
            bind.setCustomerId(customerDeviceBind.getCustomerId());
            bind.setDeviceType(deviceTypes.get(i));
            bind.setDeviceId(deviceIds.get(i));
            bind.setCreateTime(nowDate);
            bind.setCreateBy(SecurityUtils.getUsername());
            insertList.add(bind);
        }
        int i = customerDeviceBindMapper.batchInsertCustomerDeviceBind(insertList);
        //更新设备绑定信息
        CustomerManagement customerManagement = customerManagementService.selectCustomerManagementById(customerDeviceBind.getCustomerId());
        deviceMapper.updateDeviceBindByDeviceIds(deviceIds,customerDeviceBind.getCustomerId(),customerManagement.getRealName());
        return i;
    }

    /**
     * 修改用户设备绑定
     * 
     * @param customerDeviceBind 用户设备绑定
     * @return 结果
     */
    @Override
    public int updateCustomerDeviceBind(CustomerDeviceBind customerDeviceBind)
    {
        customerDeviceBind.setUpdateTime(DateUtils.getNowDate());
        return customerDeviceBindMapper.updateCustomerDeviceBind(customerDeviceBind);
    }

    /**
     * 批量删除用户设备绑定
     * 
     * @param ids 需要删除的用户设备绑定主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteCustomerDeviceBindByIds(Long[] ids)
    {
        //将设备上的绑定信息清楚
        deviceMapper.updateDeviceBindByBindIds(Arrays.asList(ids),null,null);
        return customerDeviceBindMapper.deleteCustomerDeviceBindByIds(ids);
    }

    /**
     * 删除用户设备绑定信息
     * 
     * @param id 用户设备绑定主键
     * @return 结果
     */
    @Override
    public int deleteCustomerDeviceBindById(Long id)
    {
        return customerDeviceBindMapper.deleteCustomerDeviceBindById(id);
    }

    @Override
    public List<CustomerDeviceBindVO> selectCustomerDeviceBindList2(CustomerDeviceBindVO customerDeviceBind) {
        return deviceService.selectCustomerDeviceBindList(customerDeviceBind);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertCustomerDeviceBind(String deviceNo) {
        //获取设备
        Device device = deviceService.selectDeviceByDeviceNo(deviceNo);
        if (device==null){
            throw new ServiceException("系统还没录入该设备！");
        }
        CustomerDeviceBind oldBind = customerDeviceBindMapper.selectCustomerDeviceBindByDeviceId(device.getId());
        //判断该设备是否已经绑定
        if(OwnershipEnum.CUSTOMER.getCode().equals(device.getOwnershipFlag())){
            if(oldBind!=null){
                if (oldBind.getCustomerId().equals(SecurityUtils.getUserId())){
                    throw new ServiceException("您已绑定了该设备，无需再次绑定！");
                }else {
                    throw new ServiceException("该设备已被绑定，不能多次绑定！");
                }
            }
        }else if (OwnershipEnum.STORE.getCode().equals(device.getOwnershipFlag())&&oldBind!=null){
            //删除旧的绑定关系
            customerDeviceBindMapper.deleteCustomerDeviceBindById(oldBind.getId());
        }
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        CustomerDeviceBind bind = new CustomerDeviceBind();
        bind.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
        bind.setBindTime(DateUtils.getNowDate());
        bind.setCustomerId(userId);
        bind.setDeviceId(device.getId());
        bind.setCreateTime(DateUtils.getNowDate());
        bind.setCreateBy(username);
        bind.setDeviceType(device.getType());
        int i = customerDeviceBindMapper.insertCustomerDeviceBind(bind);
        deviceMapper.updateDeviceBindByDeviceIds(Collections.singletonList(device.getId()),userId,username);
        return i;
    }
}
